#include "volumetool.h"
#include "ui_volumetool.h"
#include <QGraphicsDropShadowEffect>
#include <QPainter>
VolumeTool::VolumeTool(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::VolumeTool),
    isMute(false),
    VolumRatio(20)
{
    ui->setupUi(this);
    setWindowFlags(Qt::Popup | Qt::FramelessWindowHint|
                   Qt::NoDropShadowWindowHint);
    // 在windows上，设置透明效果后，窗⼝需要加上Qt::FramelessWindowHint格式
    // 否则没有控件位置的背景是⿊⾊的
    // 由于默认窗⼝有阴影，因此还需要将窗⼝的原有的阴影去掉，窗⼝需要加上Qt::NoDropShadowWindowHint
    setAttribute(Qt::WA_TranslucentBackground);
    // ⾃定义阴影效果
    QGraphicsDropShadowEffect* as=new QGraphicsDropShadowEffect(this);
    as->setOffset(0,0);
    as->setColor("#646464");
    as->setBlurRadius(10);
    setGraphicsEffect(as);
    // 给按钮设置图标
    ui->silenceBtn->setIcon(QIcon(":/images/volumn.png"));
    // ⾳量的默认⼤⼩是20
    ui->outSlider->setGeometry(ui->outSlider->x(), 180 - 36 +25, ui->outSlider->width(), 36);
    ui->sliderBtn->move(ui->sliderBtn->x(), ui->outSlider->y() - ui->sliderBtn->height()/2);
    ui->volumeRatio->setText("20%");
    connect(ui->silenceBtn,&QPushButton::clicked,this,&VolumeTool::onSilenctClicked);
    ui->sliderBox->installEventFilter(this);
}

void VolumeTool::paintEvent(QPaintEvent *event)
{
    (void)event;
    // 1. 创建绘图对象
    QPainter painter(this);
    // 2. 设置抗锯⻮
    painter.setRenderHint(QPainter::Antialiasing,true);
    // 3. 设置画笔
    // 没有画笔时：画出来的图形就没有边框和轮廓线
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::white);
    QPolygon polygon;
    polygon.append(QPoint(30, 315));
    polygon.append(QPoint(70, 315));
    polygon.append(QPoint(50, 335));
    painter.drawPolygon(polygon);

}

void VolumeTool::onSilenctClicked()
{
    isMute=!isMute;
    if(isMute==true)
    {
        ui->silenceBtn->setIcon(QIcon(":/images/silent.png"));
    }
    else
    {
        ui->silenceBtn->setIcon(QIcon(":/images/volumn.png"));
    }
    emit setslince(isMute);
}
bool VolumeTool::eventFilter(QObject *watch, QEvent *event)
{
    if(ui->sliderBox==watch)
    {
        if(event->type()==QEvent::MouseButtonPress)
        {
            setVolume();
        }
        else if(event->type()==QEvent::MouseButtonRelease)
        {
            emit setMusicVolume(VolumRatio);
        }
        else if(event->type()==QEvent::MouseMove)
        {
            setVolume();
            emit setMusicVolume(VolumRatio);
        }
        return true;
    }
    return QObject::eventFilter(watch,event);
}

void VolumeTool::setVolume()
{
   int height=ui->sliderBox->mapFromGlobal(QCursor().pos()).y();
   height=height<25?25:height;
   height=height>205?205:height;
   ui->sliderBtn->move(ui->sliderBtn->x(),height-ui->sliderBtn->height()/2);
   ui->outSlider->setGeometry(ui->outSlider->x(),height,ui->outSlider->width(),205-height);
   VolumRatio=(int)((int)ui->outSlider->height()/(float)180*100);
   ui->volumeRatio->setText(QString::number(VolumRatio)+"%");
}
VolumeTool::~VolumeTool()
{
    delete ui;
}
